#!/bin/bash

# SunAdmin Core NPM 包发布脚本
# 用于构建和发布 sunadmin-core 核心包

echo "🚀 SunAdmin Core 包发布工具"
echo "================================"

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_JSON="$SCRIPT_DIR/package.json"
SRC_DIR="$SCRIPT_DIR/src"
DIST_DIR="$SCRIPT_DIR/dist"

# 检查必要文件和目录
if [ ! -f "$PACKAGE_JSON" ]; then
    echo "❌ 错误: package.json 文件不存在"
    exit 1
fi

if [ ! -d "$SRC_DIR" ]; then
    echo "❌ 错误: src 目录不存在"
    exit 1
fi

# 检查 Node.js 环境
if ! command -v node &> /dev/null; then
    echo "❌ 错误: 未安装 Node.js"
    exit 1
fi

if ! command -v npm &> /dev/null; then
    echo "❌ 错误: 未安装 NPM"
    exit 1
fi

# 0. 先打包，如失败则终止
# 1. 清理 dist 目录
echo "🧹 清理 dist 目录..."
if [ -d "$DIST_DIR" ]; then
    rm -rf "$DIST_DIR"
    echo "✓ 已清理 dist 目录"
else
    echo "✓ dist 目录不存在，跳过清理"
fi

# 2. 安装依赖
echo ""
echo "📦 安装依赖..."
if npm install; then
    echo "✓ 依赖安装完成"
else
    echo "❌ 依赖安装失败"
    exit 1
fi

# 3. 构建项目
echo ""
echo "🔨 构建项目..."
echo "   执行: npm run build"
if npm run build; then
    echo "✓ 项目构建完成"
else
    echo "❌ 项目构建失败"
    exit 1
fi

# 检查构建结果
if [ ! -d "$DIST_DIR" ]; then
    echo "❌ 错误: 构建后 dist 目录不存在"
    exit 1
fi

# 检查主要文件是否存在
MAIN_FILE="$DIST_DIR/index.es.js"
if [ ! -f "$MAIN_FILE" ]; then
    echo "❌ 错误: 主文件 $MAIN_FILE 不存在"
    exit 1
fi

echo "✓ 构建文件验证通过"

# 解析 package.json 获取包信息
PACKAGE_NAME=$(node -p "require('$PACKAGE_JSON').name" 2>/dev/null)
PACKAGE_VERSION=$(node -p "require('$PACKAGE_JSON').version" 2>/dev/null)
PACKAGE_DESCRIPTION=$(node -p "require('$PACKAGE_JSON').description" 2>/dev/null)
PACKAGE_AUTHOR=$(node -p "require('$PACKAGE_JSON').author" 2>/dev/null)

# 版本号逻辑
NPM_LATEST_VERSION=$(npm view "$PACKAGE_NAME" version 2>/dev/null || echo "0.0.0")
LOCAL_VERSION=$(node -p "require('$PACKAGE_JSON').version")

# 递增 patch 版本
inc_patch() {
  local v=$1
  local major minor patch
  IFS='.' read -r major minor patch <<< "$v"
  patch=$((patch+1))
  echo "$major.$minor.$patch"
}

if [ "$NPM_LATEST_VERSION" = "0.0.0" ]; then
  NEXT_VERSION="$LOCAL_VERSION"
else
  if [ "$LOCAL_VERSION" = "$NPM_LATEST_VERSION" ]; then
    NEXT_VERSION=$(inc_patch "$NPM_LATEST_VERSION")
  elif [ "$(printf '%s\n' "$LOCAL_VERSION" "$NPM_LATEST_VERSION" | sort -V | tail -n1)" = "$NPM_LATEST_VERSION" ]; then
    # NPM 版本比本地新
    NEXT_VERSION=$(inc_patch "$NPM_LATEST_VERSION")
  else
    # 本地比 NPM 新
    NEXT_VERSION="$LOCAL_VERSION"
  fi
fi

echo "本地版本号: $LOCAL_VERSION"
echo "NPM 远程最新版本号: $NPM_LATEST_VERSION"
read -p "请输入本次发布的新版本号（直接回车将自动采用 NPM 递增版本: $NEXT_VERSION）: " INPUT_VERSION
if [ -n "$INPUT_VERSION" ]; then
  NEXT_VERSION="$INPUT_VERSION"
else
  echo "未输入，自动采用递增版本号: $NEXT_VERSION"
fi

# 写入 package.json
if [ "$NEXT_VERSION" != "$LOCAL_VERSION" ]; then
  echo "🔄 正在写入新版本号: $LOCAL_VERSION -> $NEXT_VERSION"
  
  # 写入 src/assets/version.json
  VERSION_JSON_FILE="$SRC_DIR/assets/version.json"
  # 确保 assets 目录存在
  mkdir -p "$(dirname "$VERSION_JSON_FILE")"
  # 写入版本信息
  node -e "
    const fs = require('fs');
    const versionData = {
      version: '$NEXT_VERSION',
      buildTime: new Date().toISOString(),
      buildDate: '$(date +"%Y-%m-%d %H:%M:%S")'
    };
    fs.writeFileSync('$VERSION_JSON_FILE', JSON.stringify(versionData, null, 2));
  "
  echo "✅ 版本信息已写入 src/assets/version.json"
  
  # 写入 package.json
  TMPFILE=$(mktemp)
  jq --arg v "$NEXT_VERSION" '.version = $v' "$PACKAGE_JSON" > "$TMPFILE" && mv "$TMPFILE" "$PACKAGE_JSON"
  echo "✅ package.json 版本号已更新"
fi

# 重新加载变量
PACKAGE_VERSION=$(node -p "require('$PACKAGE_JSON').version")
PACKAGE_DESCRIPTION=$(node -p "require('$PACKAGE_JSON').description" 2>/dev/null)
PACKAGE_AUTHOR=$(node -p "require('$PACKAGE_JSON').author" 2>/dev/null)

# 检查解析结果
if [ -z "$PACKAGE_NAME" ] || [ "$PACKAGE_NAME" = "null" ]; then
    echo "❌ 错误: 无法解析 package.json 中的 name 字段"
    exit 1
fi

if [ -z "$PACKAGE_VERSION" ] || [ "$PACKAGE_VERSION" = "null" ]; then
    echo "❌ 错误: 无法解析 package.json 中的 version 字段"
    exit 1
fi

# 显示包信息
echo "📋 包信息:"
echo "   名称: $PACKAGE_NAME"
echo "   版本: $PACKAGE_VERSION"
echo "   描述: $PACKAGE_DESCRIPTION"
echo "   作者: $PACKAGE_AUTHOR"
echo ""

# 检查是否已登录 npm
echo "🔐 检查 NPM 登录状态..."
if ! npm whoami > /dev/null 2>&1; then
    echo "❌ 错误: 请先登录 NPM"
    echo "   运行: npm login"
    exit 1
fi

NPM_USER=$(npm whoami)
echo "✓ 已登录 NPM，用户: $NPM_USER"
echo ""

# 检查包是否已存在并比较版本
echo "🔍 检查包版本..."
NPM_VERSION=$(npm view "$PACKAGE_NAME" version 2>/dev/null)
if [ $? -eq 0 ] && [ -n "$NPM_VERSION" ]; then
    echo "📦 NPM 上的当前版本: $NPM_VERSION"
    echo "📦 准备发布版本: $PACKAGE_VERSION"
    
    if [ "$NPM_VERSION" = "$PACKAGE_VERSION" ]; then
        echo "❌ 错误: 版本 $PACKAGE_VERSION 已存在"
        echo "   请更新 package.json 中的版本号"
        echo "   建议使用: npm version patch/minor/major"
        exit 1
    fi
else
    echo "✓ 新包或首次发布"
fi

echo ""

# 询问是否继续
echo "🤔 是否要构建并发布 $PACKAGE_NAME ?"
echo "   当前版本: $PACKAGE_VERSION"
echo "   发布步骤:"
echo "   1. 清理 dist 目录"
echo "   2. 安装依赖 (npm install)"
echo "   3. 构建项目 (npm run build)"
echo "   4. 发布到 NPM (npm publish)"
echo ""
echo -n "确认继续? (y/N): "
read -r CONFIRM

if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
    echo "❌ 取消发布"
    exit 0
fi

echo ""
echo "🔧 开始构建和发布流程..."
echo "================================"

# 0. 自动提交、打tag并推送
echo "💾 提交所有更改到git..."
git add .
echo "请输入本次发布的 commit message（如 feat: 新增xx/修复xx/发布v$PACKAGE_VERSION 等）："
read COMMIT_MSG
if [ -z "$COMMIT_MSG" ]; then
  COMMIT_MSG="release: v$PACKAGE_VERSION"
fi
git commit -m "$COMMIT_MSG" || echo "（无变更可提交）"
echo "🏷️ 打标签: v$PACKAGE_VERSION"
git tag -a "v$PACKAGE_VERSION" -m "$COMMIT_MSG" || echo "（标签已存在）"
echo "🚀 推送代码和标签到远程仓库..."
git push || true
git push --tags || true

# 4. 发布到 NPM
echo ""
echo "📤 发布到 NPM..."
if [[ "$PACKAGE_NAME" == @* ]]; then
    # 作用域包需要 --access public
    echo "📋 检测到作用域包，使用 --access public"
npm publish --access public
else
    npm publish
fi

# 检查发布结果
if [ $? -eq 0 ]; then
    echo ""
    echo "🎉 发布成功！"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "📦 包名: $PACKAGE_NAME"
    echo "🏷️ 版本: $PACKAGE_VERSION"
    echo "🌍 NPM 链接: https://www.npmjs.com/package/$PACKAGE_NAME"
    echo ""
    echo "👨‍💻 用户安装方法:"
    echo "   npm install $PACKAGE_NAME"
    echo ""
    echo "📚 更多信息:"
    echo "   - 稍等几分钟后包将在 NPM 上可用"
    echo "   - 可以通过 npm view $PACKAGE_NAME 查看包信息"
    echo "   - 构建产物已保存在 dist/ 目录"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
else
    echo ""
    echo "❌ 发布失败！"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo "🔍 可能的原因:"
    echo "   1. 网络连接问题"
    echo "   2. NPM 权限不足"
    echo "   3. 版本号冲突"
    echo "   4. 包名被占用"
    echo "   5. 文件缺失或损坏"
    echo ""
    echo "🛠️ 解决方案:"
    echo "   1. 检查网络连接"
    echo "   2. 确认 NPM 登录: npm whoami"
    echo "   3. 更新版本号: npm version patch"
    echo "   4. 检查构建产物: ls -la dist/"
    echo "   5. 重新构建: npm run build"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit 1
fi